class Subject < ActiveRecord::Base
  belongs_to :educational_plan

  has_many :groups
  has_many :equivalent_subjects,
    :class_name => 'Subject',
    :finder_sql => 'SELECT s.* FROM subjects AS s, equivalent_subjects AS es WHERE s.id = es.equivalent_to_id AND es.subject_id = #{id}',
    :counter_sql => 'SELECT count(*) from equivalent_subjects AS es WHERE es.subject_id = #{id}'

  has_many :serial_subjects,
    :class_name => 'Subject',
    :finder_sql => 'SELECT s.* FROM subjects AS s, serial_subjects AS ss WHERE s.id = ss.requisite_id AND ss.subject_id = #{id}',
    :counter_sql => 'SELECT count(*) from serial_subjects AS ss WHERE ss.subject_id = #{id}'


  validates_presence_of :name, :abbreviation, :code, :educational_plan_id, :term_number,
    :credits, :info, :bibliography
  validates_uniqueness_of :code
  validates_numericality_of :term_number, :only_integer => true, :greater_than => 0
  validates_numericality_of :credits, :only_integer => true, :greater_than => 0

  validate :optional_stub

  protected
  def optional_stub
    errors.add(:is_optional_stub, 'La materia no puede ser obligatoria y relleno al mismo tiempo.') if is_optional_stub && is_required
  end
end
